const express = require('express');
const router = express.Router();
const { Article } = require('../../models');  
const { Op } = require('sequelize');  //模糊匹配查询
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');
//列表查询 
router.get('/', async function(req, res, next) {
    try{
   
    //当前是第几页  
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    //每页显示多少条
    const pageSize = Math.abs(Number(req.query.pageSize))|| 10;
    //计算 offset
    const offset = (currentPage - 1) * pageSize; 

    const condition ={  //倒序
        order:[['id','desc']],
        limit: pageSize,
        offset
    } 
    if(req.query.title){  //模糊匹配
        condition.where = { 
            title: {
                [Op.like]: `%${req.query.title}%`
            }
        }
    }  
    // const articles =await Article.findAll(condition)
    const {count ,rows} =await Article.findAndCountAll(condition)
    success(res,'success', {
        articles: rows,
        pagination: {
            total: count,
            currentPage,
            pageSize
        } 
    },200)
    }catch(err){
        failure(res,err)
    }
});
//新增
router.post('/', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const article = await Article.create(body)
        success(res,'success', article,201)
        }catch(err){
            failure(res,err)
        }
});
//id占位查询
router.get('/:id', async function(req, res, next) {
    try{
        const article = await getArticle(req)
        success(res,'success', article,201)
    }catch(err){
        failure(res,err)
    }
});
//删除文章
router.delete('/:id', async function(req, res, next) {
    try{
    const article = await getArticle(req)
    await article.destroy()
        success(res,'success', {
            status: true,
            msg: '删除成功',
        },201)
    }catch(err){
        failure(res,err)
    }
})
//修改文章
router.put('/:id', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const article = await getArticle(req)
        await article.update(body)
        success(res,'success', {
            status: true,
            msg: '更新成功',
            data:{article}
        },200)
    }catch(err){
        failure(res,err)
    }
})


const bodyFilter = ['title','content']
function filterBody(body) {
    const result = {}
    bodyFilter.forEach(key => {
        if(body[key]){
            result[key] = body[key]
        }
    })
    return result
}
async function getArticle(req) {
    const { id } = req.params;
    const article = await Article.findByPk(id)
    if( !article ) throw new NotFoundError(`ID:${id} 的文章不存在`)
    return article
}
module.exports = router;
